<template>
    <div style="width: 100%;">
        <div id="container" class="map"></div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue"
import AMapLoader from "@amap/amap-jsapi-loader";
import { api_orders_dispatch } from "~/api/ordersApi";
import { api_location_nearestEngineer } from "~/api/locationApi";
import { toast, toastWarn } from '~/composables/util'
import icons from '~/assets/poi-marker.png'

//props
const props = defineProps({
    assignMapProps: Object,
})

//工单附近的工程师列表
const engineerList = ref([])

//选择的派发工程师IDS
const assignedUserId = ref([])

const state = reactive({
    map: null,
    placeSearch: null,
    autoComplete: null,
    marker: null,
    form: {
        address: '',
        lng: '',
        lat: '',
    },
    areaList: [],
    address: '',
    assignedUserId: null
})

// 生命周期函数
onMounted(async () => {

    // 绑定onClick选中事件
    window["selectedEngineer"] = selectedEngineer

    //已经选择的进行赋值
    if(null != props.assignMapProps.assignedUserId && props.assignMapProps.assignedUserId.length>0){
        assignedUserId.value = props.assignMapProps.assignedUserId
    }
    console.log(JSON.stringify(assignedUserId.value))


    //console.log('props.assignMapProps===>', JSON.stringify(props.assignMapProps))

    //根据经纬度获取工程师列表
    await getTargetLocationArroundEngineer(props.assignMapProps)

    console.log('load map======')

    window._AMapSecurityConfig = {
        securityJsCode: '8ffe92977bb0f5d65f8cf83a59a5186b', // https://console.amap.com/dev/key/app   绑定的服务为 Web端
    }
    //清除之前的加载状态
    AMapLoader.reset()
    //initMap([116.412838, 39.908021])
    //加载地图 
    //console.log('props 经纬度：', [props.assignMapProps.orderLocationDto.longitude, props.assignMapProps.orderLocationDto.latitude])
    initMap([props.assignMapProps.orderLocationDto.longitude, props.assignMapProps.orderLocationDto.latitude],props.assignMapProps.orderLocationDto.formattedAddress)
})

onUnmounted(() => {
    console.log("select-engineer-map.vue 销毁地图===")
    state.map?.destroy();
});

// 获取目标地址附近的工程师列表
async function getTargetLocationArroundEngineer(newProps) {
    let longitude = newProps.orderLocationDto.longitude
    let latitude = newProps.orderLocationDto.latitude
    //console.log("getTargetLocationArroundEngineer===req===>",longitude,latitude)
    await api_location_nearestEngineer(longitude, latitude, 20).then(res => {
        //console.log("getTargetLocationArroundEngineer===res===>",JSON.stringify(res))
        engineerList.value = res
    })
}

// 派单
// function submitAssign(row) {
//     if (state.assignedUserId == row.wxUserDto.id || state.assignedUserId) {
//         toastWarn('已分配工程师')
//         return
//     }
//     let reqParams = {
//         orderId: props.assignMapProps.orderDto.orderId,
//         engineerId: row.wxUserDto.id
//     }
//     api_orders_dispatch(reqParams)
//     .then(res => {
//         console.log('dispatch res: ', res)
//         toast('指派工程师成功', 'success')
//         state.assignedUserId = row.wxUserDto.id
//         getTargetLocationArroundEngineer(props.assignMapProps)
//     })
// }


// init地图

// 初始化地图
function initMap(arr,formattedAddress) {
    //console.log("初始化中心点===>",arr,formattedAddress)
    AMapLoader.load({
        key: "c589dad363492c5cd9ba0b62950a9dc8",
        version: "2.0",
        plugins: ["AMap.ToolBar", "AMap.ControlBar", 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder', 'AMap.Marker', 'AMap.Geolocation'],
    }).then((AMap) => {
        state.map = new AMap.Map('container', {
            //是否为3D地图模式
            viewMode: "2D",  
            //地图容器能够响应尺寸变化
            resizeEnable: true,
            //初始地图缩放级别
            zoom: 12,
            center: arr
        });

        //工单位置标注
        var layer = new AMap.LabelsLayer({
            zooms: [3, 20],
            zIndex: 1000,
            // 设置 allowCollision：true，可以让标注避让用户的标注
            allowCollision: true,
            // 开启标注淡入动画，默认为开启，v1.4.15 新增属性
            collision: true,
        });
        state.map.add(layer)
        let targetLocation = new AMap.LabelMarker({
            //标注名称，作为标注标识，并非最终在地图上显示的文字内容，显示文字内容请设置 opts.text.content
            name: '工单地点',
            position: arr,
            //标注透明度，默认值: 1
            opacity: 1,
            //同一 LabelsLayer 内标注显示层级，数字越大越靠前，默认值: 1
            zIndex: 10,
            //标注图标设置
            icon: {
                type: 'image',
                image: 'https://vdata.amap.com/icons/b18/1/2.png',
            },

            //标注文本设置
            text: {
                //文本标注的内容，该属性为直接显示在标注上的文本内容。
                content: '工单地点',
                // 可选值：'top'|'right'|'bottom'|'left'|'center'
                direction: 'top',
                //为偏移量，在 direction 基础上的偏移。默认值 [0, 0]
                offset: [0, 0],
            }
        })
        layer.add(targetLocation)

        //标注工程师位置
        if(null != engineerList.value && engineerList.value.length>0){
            for (var i = 0; i < engineerList.value.length; i++) {
                var engineer = engineerList.value[i]
                //console.log("engineerInfo===>",JSON.stringify(engineer))

                //工程师地图标注
                let marker1 = new AMap.Marker({
                    position: [engineer.locationDto.longitude, engineer.locationDto.latitude],
                    icon: new AMap.Icon({
                        image: icons, // 图标的图片地址
                        size: new AMap.Size(80, 70), // 图标的尺寸
                        //imageSize: new AMap.Size(25, 34), // 图片的实际尺寸大小
                        imageOffset: new AMap.Pixel(-700,-8), // 图标相对于其位置的偏移量
                    }),
                    extData: engineer.wxUserDto.id
                });

                // 添加点击事件
                marker1.on('click', () => {
                    // 使用 document.getElementById() 获取 div 元素
                    const div = document.getElementById('enInfo'+marker1.getExtData());
                    // 切换显示与隐藏
                    if (div) {
                        div.style.display = div.style.display === 'none' ? 'block' : 'none';
                    }
                });

                //工程师状态
                if(engineer.wxUserDto.dailyState==0){
                    engineer.wxUserDto.dailyStateDesc="闲"
                }else{
                    engineer.wxUserDto.dailyStateDesc="忙"
                }

                //是否被选中
                let inputHtml = ""
                let index = assignedUserId?.value.findIndex(x => x == engineer.wxUserDto.id)
                if(index != -1){
                    inputHtml = '<input type="checkbox" checked onclick="selectedEngineer('+ engineer.wxUserDto.id +')" style="width: 20px;height: 20px; position: absolute;top: -10px;left: -10px;">';
                }else{
                    inputHtml = '<input type="checkbox" onclick="selectedEngineer('+ engineer.wxUserDto.id +')" style="width: 20px;height: 20px; position: absolute;top: -10px;left: -10px;">';
                }

                //工程师信息窗体
                var marker2 = new AMap.Marker({
                    position: [engineer.locationDto.longitude, engineer.locationDto.latitude],
                    offset: [-120,-80],
                    content: '<div id="enInfo'+ engineer.wxUserDto.id +'" style="background-color: white;width: 180px;height: 80px;font-size: 15px;border-radius: 10px;padding: 5px;">'+
                        inputHtml +                        
                        '<span style="margin-left: 10px;">工程师: '+engineer.wxUserDto.realName+'</span>'+
                        '<br/><span style="margin-left: 10px;">电话: '+engineer.wxUserDto.phone+'</span>'+
                        '<br/><span style="margin-left: 10px;">状态: '+engineer.wxUserDto.dailyStateDesc+'</span>'+
                        '</div>'
                });

                let markers = [marker1, marker2];
                state.map.add(markers);
            }
        }

        //根据地图上添加的覆盖物分布情况，自动缩放地图到合适的视野级别，参数均可缺省。
        state.map.setFitView();

    }).catch((e) => {
        console.error(e);  //加载错误提示
    })
}

//工程师选中触发事件
const selectedEngineer = (id) => {

    //console.log("select user id ===>", id)

    //判断已选择工程师是否已经存在
    let index = assignedUserId?.value.findIndex(x => x == id)
    if (index != -1) {
        //取消派发
        assignedUserId.value.splice(index, 1)
    } else {
        //派发
        assignedUserId.value.push(id)
    }
    //console.log("align user ids ===>", assignedUserId.value)

    //传递给调用者
    getCheckedMapEngineer()
};

// 对外暴露方法
const emit = defineEmits([
    'getCheckedMapEngineer',
])

const getCheckedMapEngineer = () => {
    const selectData = assignedUserId
    let returnParams = selectData.value
    emit("getCheckedMapEngineer", returnParams)
}
</script>

<style scoped lang="scss">
.map {
    width: 1180px;
    height: 580px;
    padding-top: 20px;
}

#container {
    margin-top: 20px;
    border-radius: 5px;
}

.search-box {
    display: flex;
}

.address {
    margin-left: 20px;
}
</style>